﻿using System;
using System.Windows;
using Ping.Core;

namespace Ping.Watchdog
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow
	{
		private readonly Connection _connection;

		public MainWindow()
		{
			InitializeComponent();

			_connection = new Connection();
			Loaded += WindowLoaded;
		}

		private void WindowLoaded(object sender, RoutedEventArgs e)
		{
			_connection.Request(new StatusRequest(), EndRequest);
		}

		private void EndRequest(Result result, Exception e)
		{
			Dispatcher.BeginInvoke(new Action(() => EndRequestSafe(result, e) ));
		}

		private void EndRequestSafe(Result result, Exception e)
		{
			if (result is StatusResult)
			{
				var res = (StatusResult) result;

				status.Text = "Running";
				uptime.Text = res.Uptime.Format();
				numConnections.Text = string.Format("{0}", res.NumConnections);
				numBlacklisted.Text = string.Format("{0}", res.NumBlacklistedIPs);
				privateMemory.Text = Extensions.FormatSize(res.PrivateMemory);
				peakVirtMemory.Text = Extensions.FormatSize(res.PeakVirtualMemory);
				pagedProcMemory.Text = Extensions.FormatSize(res.PagedProcessMemory);
				peakPagedMemory.Text = Extensions.FormatSize(res.PeakPagedMemory);
				pagedSystemMem.Text = Extensions.FormatSize(res.PagedSystemMemory);
				nonpagedSystemMem.Text = Extensions.FormatSize(res.NonpagedSystemMemory);
				numThreads.Text = string.Format("{0}", res.NumThreads);
			}
			else
			{
				status.Text = "Unavailable";
				uptime.Text = "n/a";
				numConnections.Text = "n/a";
				numBlacklisted.Text = "n/a";
				privateMemory.Text = "n/a";
				peakVirtMemory.Text = "n/a";
				pagedProcMemory.Text = "n/a";
				peakPagedMemory.Text = "n/a";
				pagedSystemMem.Text = "n/a";
				nonpagedSystemMem.Text = "n/a";
				numThreads.Text = "n/a";
			}
		}

		private void UpdateClicked(object sender, RoutedEventArgs e)
		{
			_connection.Request(new StatusRequest(), EndRequest);
		}
	}
}